﻿package net.wangit.user;

import net.wangit.Element;
import net.wangit.framework.action.ActionMapping;
import net.wangit.util.StringUtil;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitFactory;

public class LimitedSuperUser extends RegisteredUser {

	private static final long serialVersionUID = 1L;
	private static String PRIVATE_DOMAIN = "adm";
	private static String PRIVATE_GROUP = "admin";

	protected LimitedSuperUser(String id) {
		super(id);
	}

	public boolean hasUnitPrivilege(String domain, String unitId,
			String unitShowMode) {
		boolean pass = super.hasUnitPrivilege(domain, unitId, unitShowMode);
		if (pass) {
			return true;
		} else {
			UnitComponent uc = UnitFactory.getUnitWithoutClone(domain, unitId);
			return isPrivateUnitGroup(domain, uc.getGroupId());
		}
	}

	public boolean hasActionPrivilege(ActionMapping am) {
		return super.hasActionPrivilege(am)
				|| isPrivateUnitGroup(am.getDomain(), am.getGroupId());
	}

	public boolean hasElementPrivilege(Element element) {
		if (super.hasElementPrivilege(element)) {
			return true;
		} else {
			UnitComponent uc = ((ElementComponent) element).getParent();
			return isPrivateUnitGroup(uc.getDomain(), uc.getGroupId());
		}
	}

	public boolean hasDataPrivilege(Object key) {
		if (super.hasDataPrivilege(key)) {
			return true;
		} else {
			String params[] = StringUtil.split((String) key, ",");
			UnitComponent uc = UnitFactory.getUnitWithoutClone(params[0],
					params[2]);
			return isPrivateUnitGroup(params[0], uc.getGroupId());
		}
	}

	private boolean isPrivateUnitGroup(String domain, String groupId) {
		return PRIVATE_DOMAIN.equals(domain) && PRIVATE_GROUP.equals(groupId);
	}

}
